package com.xc.pay.ali;

import cn.hutool.core.lang.Console;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.response.*;
import com.xc.pay.AliPayProperties;
import com.xc.pay.ali.constant.AliProperties;
import com.xc.pay.ali.enums.PayeeInfoTypeEnum;
import com.xc.pay.ali.enums.ProductCodeEnum;
import com.xc.pay.common.OutTradeNoUtil;
import com.xc.pay.common.PayTypeEnum;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试类
 *
 * @author rongrong
 * @date 2020/11/26
 */
public class AliPayTest {

  private static final String notifyUrl = "http://www.oyygke.top/";
  private static final String loginName = "bwpiny6452@sandbox.com";
  private static final String appid = "2016091500517988";
  private static final String serverId = "2088102175759801";
  private static final String privateKey =
      "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDikCywRSfiLorsovCmORNjTVtAPvVYSEMM1E8Ri+sruiF3hIzRTNfsXjLOJtmz7/6+YDQ5o8jPmzZcSFxLg9oEH7BZg6LckBAR0tyUNsxz1h9M9Cd9DjsNbMmRE1n1QCSPH0oB62sFooa5s51/Ak6yVm+o8LeH4vtq8k+BNcivfHjli9A7DSBQoyUuD5gMoDLfnXZ0yYfOCgnY1fsB6rJcZ2Om4FZlGW1uK1nuoz/f2KcIRNjWVJlUbJuyt+JcQLrmQcT60Xs1oxm5dcQ4fuOPj39Vjw7I2hH9IPo4SbxF44ymr8y/lI3I8wbpYS3Qin9d6cdSN/ytkZ+sfE9kiZU3AgMBAAECggEBANY5nQfPXDbx60p1hzalIT/0FSRaY4JmUYAAAAOHWYavKJXqL3x4PHKzXzauZYtOkoFQVhFqXKZxDKWVhi+hLLRZglYhsgz76zXvO8KpTgj5nf8VnYERw6SeCLm0oorTa74ox8Go6DkbxGgy/ejqNZ9LO6lycxd5+GDXXXW/dVL3h2klZLhQKBUQK1ZklE2dL+41nnUp0hnPshnpq1jKmmbCgX/8YO4iTm9vSQ3aeYOo2sR6+iEx2GN3Rvl1Q/cRs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NYk5ue0jQSwGx/ZKzsHZixjTNxnF/Nz9JfHiYzQZrzf3ximPfAJ6hjrlHZLKa7g+3ZcnajE6tkzQrDjS8RsvN/ODhOLdphFV0IeXTnzeGbGlUcjVOiFFe1jdrS8artUWKmCqXfifg0e5A6gjLOkH0CXwYL3yQeeGldKalKzlftsKW8xX0axrMnd1zIKDqtUhgBRdpr3ruVVxJy5VE6PWXMM61Ltp6Q+2TABRdukGwNXbyh4UsZBCMLr6SxNVmFGaazIU7bjSmRP0WMe63lc9msu6QDrCwIDAQAB";
  private static AliPayTemplate template;

  static {
    final AliPayProperties properties = new AliPayProperties();
    properties
        .setEnable(true)
        .setSandbox(true)
        .setAppid(appid)
        .setServerId(serverId)
        .setAppPrivateKey(privateKey)
        .setAliPublicKey(publicKey);
    template =
        AliPayTemplate.build(AliProperties.SANDBOX_URL, appid, privateKey, publicKey, properties);
  }

  public static void appPay() {
    final AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
    // 内容
    model.setBody("测试");
    // 订单号
    final String tradeNo = OutTradeNoUtil.createTradeNo(PayTypeEnum.ALI);
    System.err.println("订单号：" + tradeNo);
    model.setOutTradeNo(tradeNo);
    // 标题
    model.setSubject("支付测试");
    // 支付金额
    model.setTotalAmount("99");
    try {
      final String sign = template.appPay(model, notifyUrl);
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void nativePay() {
    final AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
    // 内容
    model.setBody("测试");
    // 订单号
    model.setOutTradeNo(System.currentTimeMillis() + "");
    // 标题
    model.setSubject("支付测试");
    // 支付金额
    model.setTotalAmount("0.01");
    try {
      final String sign = template.customerNativePay(model, notifyUrl);
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void merchantNativePay() {
    final AlipayTradePayModel model = new AlipayTradePayModel();
    // 内容
    model.setBody("测试");
    // 订单号
    model.setOutTradeNo(System.currentTimeMillis() + "");
    // 标题
    model.setSubject("支付测试");
    // 支付金额
    model.setTotalAmount("0.01");
    // 支付场景
    model.setScene(AliProperties.BAR_CODE);
    // 支付宝支付条形码下的数字
    model.setAuthCode("287917325685791019");
    try {
      final String sign = template.merchantNativePay(model, notifyUrl);
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void wapPay() {
    final AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
    // 内容
    model.setBody("测试");
    // 订单号
    model.setOutTradeNo(System.currentTimeMillis() + "");
    // 标题
    model.setSubject("支付测试");
    // 支付金额
    model.setTotalAmount("0.01");
    try {
      final String sign = template.wapPay(model, notifyUrl, null);
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void pcPay() {
    final AlipayTradePagePayModel model = new AlipayTradePagePayModel();
    // 内容
    model.setBody("测试");
    // 订单号
    model.setOutTradeNo(System.currentTimeMillis() + "");
    // 标题
    model.setSubject("支付测试");
    // 支付金额
    model.setTotalAmount("0.01");
    model.setQrPayMode("4");
    model.setQrcodeWidth(150L);
    try {
      final String sign = template.pcPay(model, notifyUrl);
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void zhuanzhang() {
    final AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
    // 内容
    model.setOrderTitle("测试");
    // 订单号
    model.setOutBizNo(System.currentTimeMillis() + "");
    // 支付金额
    model.setTransAmount("0.01");
    final Participant participant = new Participant();
    participant.setIdentityType(PayeeInfoTypeEnum.ALIPAY_LOGON_ID.getVal());
    participant.setIdentity(loginName);
    participant.setName("沙箱环境");
    model.setPayeeInfo(participant);
    try {
      final String sign =
          template.transferAccounts(model, ProductCodeEnum.TRANS_ACCOUNT_NO_PWD, notifyUrl);
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void toCode() {
    try {
      final String sign = template.userInfoAuth();
      Console.log("成功：{}", sign);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void refund() {
    try {
      final AlipayTradeRefundModel model = new AlipayTradeRefundModel();
      model.setOutTradeNo("ALI3816230637006918731");
      model.setRefundAmount("99");
      final AlipayTradeRefundResponse response = template.refundOrder(model);
      Console.log("退款成功：{}", response.getBuyerUserId());
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void queryOrder() {
    try {
      final AlipayTradeQueryModel model = new AlipayTradeQueryModel();
      //      model.setOutTradeNo("ALI3160653788044859767");
      model.setTradeNo("2020112622001489180501044646");
      final AlipayTradeQueryResponse response = template.queryOrderInfo(model);
      // WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
      Console.log("支付宝交易号：{}", response.getTradeNo());
      Console.log("商户交易号：{}", response.getOutTradeNo());
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void tradeCreate() {
    try {
      final AlipayTradeCreateModel model = new AlipayTradeCreateModel();
      // 内容
      model.setBody("测试订单创建");
      // 订单号
      final String tradeNo = OutTradeNoUtil.createTradeNo(PayTypeEnum.ALI);
      System.err.println("订单号：" + tradeNo);
      model.setOutTradeNo(tradeNo);
      // 标题
      model.setSubject("创建订单");
      // 支付金额
      model.setTotalAmount("99");
      model.setBuyerLogonId(loginName);
      final AlipayTradeCreateResponse response = template.tardeCreate(model, notifyUrl);
      Console.log("订单号：{}", response.getOutTradeNo());
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void tardeClose() {
    try {
      final AlipayTradeCloseModel model = new AlipayTradeCloseModel();
      model.setOutTradeNo("ALI3160653788044859767");
      final AlipayTradeCloseResponse response = template.tardeClose(model);
      Console.log("订单号：{}", response.getOutTradeNo());
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void tradeOrderSettle() {
    try {
      final AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
      model.setTradeNo("2020112622001489180501044656");
      model.setOutRequestNo(OutTradeNoUtil.createTradeNo(PayTypeEnum.ALI));
      final List<OpenApiRoyaltyDetailInfoPojo> infoPojos = new ArrayList<>();
      final OpenApiRoyaltyDetailInfoPojo pojo = new OpenApiRoyaltyDetailInfoPojo();
      pojo.setTransIn(loginName);
      pojo.setTransInType(loginName);
      pojo.setAmount("10");
      infoPojos.add(pojo);
      model.setRoyaltyParameters(infoPojos);
      final String response = template.tardeOrderSettle(model);
      Console.log("支付宝交易号：{}", response);
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void refundQuery() {
    try {
      final AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
      model.setTradeNo("2020112622001489180501044646");
      model.setOutRequestNo("ALI3816230637006918731");
      final AlipayTradeFastpayRefundQueryResponse response = template.refundQuery(model);
      Console.log(
          "返回：{},{},{}",
          response.getRefundStatus(),
          response.getTotalAmount(),
          response.getRefundAmount());
    } catch (AlipayApiException e) {
      Console.log(e.getMessage());
    }
  }

  public static void main(String[] args) {
    // app支付
    // appPay();
    // 顾客扫码付
    // nativePay();
    // 商家扫码
    // merchantNativePay();
    // 手机网站支付
    // wapPay();
    // PC支付
    // pcPay();
    // 单笔转账
    // zhuanzhang();
    // 退款接口
    // refund();
    // 订单查询
    //     queryOrder();
    // 订单创建
    // tradeCreate();
    // 订单关闭
    // tardeClose();
    // 订单结算
    // tradeOrderSettle();
    // 退款查询
    refundQuery();
  }
}
